import React, { PureComponent } from "react";
import { View, StyleSheet, SafeAreaView, Text, TextInput, Image, BackHandler, DeviceEventEmitter, TouchableOpacity, ToastAndroid } from "react-native";
import NetInfo from "@react-native-community/netinfo";
import { Button, Icon } from "react-native-tengits-elements";
import LoadingUtil from "../common/Utils/LoadingUtil";
import Utils from "../libs/Utils";
import XLog from "../libs/XLog";
import DataCenter from "../logic/DataCenter";
import { RegisterType } from "../logic/LogicConstant";
import MainLogicLoop from "../logic/Main";
import { Colors, FontSize } from "../common/Theme/TTheme";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import { scaleSize } from "../common/Utils/ToolUtils";
import { fixRemoteIp } from "../logic/TestDataGenerate";
import { checkIpValid } from "../logic/Utils";
import { SIMULATE_MODE } from "../common/Storage/Const";

export default class RegisterDevicePage extends React.PureComponent {
    constructor(props) {
        super(props);
        this.clickTime = 0;
        this.clickCount = 0;
        this.state = {
            localCabinet: DataCenter.getLocalCabinetData(),
            cacheRegisterStatus: DataCenter.registerStatus,
            registerStatus: DataCenter.registerStatus,
            machineIp: null,
            serverIp: DataCenter.serverIp,
            machineCode: DataCenter.machineCode,
            registerError: DataCenter.registerError,
        };
    }

    async componentDidMount() {
        let ip = await Utils.getMachineIp();
        this.setState({
            machineIp: ip,
        });
        BackHandler.addEventListener("hardwareBackPress", this.onBackAndroid);
        this.netListener = NetInfo.addEventListener(async(state)=>{
                const{isConnected} = state;
                if(isConnected) {
                    this.setState({machineIp: await Utils.getMachineIp()});
                }
        });
        this.localCabinetListener = DeviceEventEmitter.addListener("register", ()=>{
            this.setState({
                cacheRegisterStatus: DataCenter.registerStatus,
                registerStatus: DataCenter.registerStatus,
                serverIp: DataCenter.serverIp,
                machineCode: DataCenter.machineCode,
                registerError: DataCenter.registerError,
                localCabinet: DataCenter.getLocalCabinetData(),
            });
        });
    }

    componentWillUnmount() {
        BackHandler.removeEventListener("hardwareBackPress", this.onBackAndroid);
        this.localCabinetListener.remove();
        this.netListener();
    }

    onBackAndroid = ()=>{
        const{navigation} = this.props;
        navigation.replace("Main");
        return true;
    }

    renderInit() {
        const{navigation} = this.props;
        const{machineIp, serverIp, machineCode, cacheRegisterStatus} = this.state;
        return <View style={{flex:1, flexDirection:'column'}}>
                <View style={styles.cardContainer}>
                    <View style={{height:scaleSize(72), alignItems:'center',justifyContent:'center', backgroundColor: Colors.yellow_color}}>
                        <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{cacheRegisterStatus ? "编辑注册信息" : "未注册"}</Text>
                    </View>
                    <View style={{flex:1, paddingHorizontal: scaleSize(70), marginTop:scaleSize(60), flexDirection:'row'}}>
                        <Image style={{width:scaleSize(160), height:scaleSize(160)}} source={require("../../images/unknown.png")}/>
                        <View style={{justifyContent:'space-between', flexDirection:'column', marginLeft:scaleSize(67)}}>
                            <View style={{flexDirection:'row', alignItems:'center', }}>
                            <Text style={{color:Colors.text1_color, width:scaleSize(220), textAlign:'right', fontSize: FontSize.h3_font}}>
                                <Text style={{color: Colors.tip_color}}>{"*"}</Text>{"服务器地址:"}</Text>
                            <TextInput
                                style={styles.input}
                                defaultValue={serverIp}
                                placeholder='请输入'
                                onChangeText={(value)=>{
                                    this.setState({serverIp: value});
                                }}
                                />
                            </View>
                            <View style={{flexDirection:'row', alignItems:'center',}}>
                            <Text style={{color:Colors.text1_color, width:scaleSize(220), textAlign:'right', fontSize: FontSize.h3_font}}>
                                <Text style={{color: Colors.tip_color}}>{"*"}</Text>{"设备编号:"}</Text>
                            <TextInput
                                style={styles.input}
                                defaultValue={machineCode}
                                placeholder='请输入'
                                onChangeText={(value)=>{
                                    this.setState({machineCode: value});
                                }}
                                />
                            </View>
                            <View style={{flexDirection:'row', alignItems:'center'}}>
                            <Text style={{color:Colors.text1_color, width:scaleSize(220), fontSize: FontSize.h3_font, textAlign:'right'}}>{"本机IP地址:"}</Text>
                            <TextInput
                                style={[styles.input, {borderWidth:0, backgroundColor: Colors.white}]}
                                editable={false}
                                defaultValue={machineIp}
                                placeholder='请连接网络'
                                />
                            </View>
                        </View>
                    </View>
            </View>
            <View style={{marginTop:scaleSize(32), flexDirection:'row', alignItems:'flex-end', justifyContent:'center'}}>
                <Button 
                    buttonStyle={styles.cancelBtn}
                    titleStyle={{color: Colors.text1_color, fontSize: FontSize.h4_font}}
                    title={"取消"} onPress={()=>{
                    if(cacheRegisterStatus == 0) {
                        navigation.replace("Main");
                    } else {
                        this.setState({
                            registerStatus: DataCenter.registerStatus,
                            serverIp: DataCenter.serverIp,
                            machineCode: DataCenter.machineCode,
                            registerError: DataCenter.registerError,
                        });
                    }
                }}/>
                <Button buttonStyle={styles.sureBtn} 
                    title={"提交"}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    onPress={async()=>{
                    if(!this.state.serverIp || this.state.serverIp.length <= 4) {
                        ToastAndroid.show("请先输入服务器地址", ToastAndroid.SHORT);
                        return;
                    }
                    if(!this.state.machineCode || this.state.machineCode.length < 1) {
                        ToastAndroid.show("请先输入设备编号", ToastAndroid.SHORT);
                        return;
                    }
                    LoadingUtil.showLoading();
                    try{
                        MainLogicLoop.uninstallMainLoop();
                        DataCenter.machineIp = await Utils.getMachineIp();
                        await DataCenter.doRegister(this.state.serverIp, this.state.machineCode);
                        let ret = await MainLogicLoop.doRegisterLogic(this.state.serverIp, this.state.machineCode);
                        if(ret == RegisterType.REGISTER_SUCCESS) {
                            await MainLogicLoop.uninstallMainLoop();
                            await MainLogicLoop.installMainLoopLogic();
                        } else {
                            ToastAndroid.show("未成功注册，软件无法正常使用", ToastAndroid.SHORT);
                        }
                    }catch(error) {
                        XLog.e("exception:",error?.message);
                    }
                    LoadingUtil.dismissLoading();
                }}/>
                {SIMULATE_MODE && <Button buttonStyle={styles.sureBtn} 
                    title={"debug"}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    onPress={async()=>{
                        navigation.navigate("Debug");
                }}/>}
            </View>
        </View>
    }

    renderOver() {
        const{machineIp, serverIp, machineCode} = this.state;
        return <View style={{flex:1, flexDirection:'column'}}>
            <View style={styles.cardContainer}>
                {this.renderTipHeader()}
                <View style={{flex:1, paddingHorizontal: scaleSize(70), marginTop:scaleSize(60), flexDirection:'row'}}>
                    <Image style={{width:scaleSize(160), height:scaleSize(160)}} source={this.getTipImage()}/>
                    <View style={{flexDirection:'column', justifyContent:'space-between', marginLeft:scaleSize(67)}}>
                        <View style={{height:scaleSize(72),flexDirection:'row', alignItems:'center', }}>
                            <Text style={{color:Colors.text1_color, width:scaleSize(220), textAlign:'right', fontSize: FontSize.h3_font}}>
                                <Text style={{color: Colors.tip_color}}>{"*"}</Text>{"服务器地址："}</Text>
                            <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{serverIp}</Text>
                        </View>
                        <View style={{height:scaleSize(72), flexDirection:'row', alignItems:'center', }}>
                            <Text style={{color:Colors.text1_color, width:scaleSize(220), textAlign:'right', fontSize: FontSize.h3_font}}>
                                <Text style={{color: Colors.tip_color}}>{"*"}</Text>{"设备编号："}</Text>
                            <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{machineCode}</Text>
                        </View>
                        <View style={{height:scaleSize(72), flexDirection:'row', alignItems:'center', }}>
                            <Text style={{color:Colors.text1_color, width:scaleSize(220), textAlign:'right', fontSize: FontSize.h3_font}}>{"本机IP："}</Text>
                            <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{machineIp}</Text>
                        </View>
                    </View>
                    <Button containerStyle={{position:'absolute', top: 0, right:scaleSize(88)}} 
                        buttonStyle={{width:scaleSize(178), height:scaleSize(64), paddingVertical:0, backgroundColor: Colors.button_color}} 
                        titleStyle={{fontSize: FontSize.h4_font}}
                        title={"编辑"}
                        onPress={()=>{
                        this.setState({
                            registerStatus: 0,
                        })
                    }}/>
                </View>
            </View>
        </View>
    }

    renderTipHeader() {
        const{registerStatus} = this.state;
        if(registerStatus == RegisterType.REGISTER_NO_NET) {
            return this.renderCacheHeader();
        } else if(registerStatus == RegisterType.REGISTER_ERROR) {
           return this.renderErrorHeader();
        } else if(registerStatus == RegisterType.REGISTER_SUCCESS) {
               return this.renderSuccessHeader();
        } else {
            return null;
        }
    }

    getTipImage() {
        const{registerStatus} = this.state;
        if(registerStatus == RegisterType.REGISTER_NO_NET) {
            return require("../../images/loading.png");
        } else if(registerStatus == RegisterType.REGISTER_ERROR) {
           return require("../../images/error.png");
        } else if(registerStatus == RegisterType.REGISTER_SUCCESS) {
               return require("../../images/success.png");
        } else {
            return require("../../images/unknown.png");
        }
    }

    renderCacheHeader() {
        return <View style={{height:scaleSize(72), alignItems:'center',justifyContent:'center', backgroundColor: Colors.yellow_color}}>
        <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{"已提交，网络不通，等待注册中"}</Text>
        </View>
    }

    renderErrorHeader() {
        const{registerError} = this.state;
        return <View style={{height:scaleSize(72), alignItems:'center',justifyContent:'center', backgroundColor: "#FED8D8"}}>
        <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{`${registerError||"请求超时"}`}</Text>
        </View>
    }

    renderSuccessHeader() {
        return <View style={{height:scaleSize(72), alignItems:'center',justifyContent:'center', backgroundColor: "#BCF1FF"}}>
        <Text style={{color:Colors.text1_color, fontSize: FontSize.h3_font}}>{"已注册"}</Text>
    </View>
    }

    renderContent() {
        const{registerStatus} = this.state;
        if(registerStatus == RegisterType.REGISTER_NO_NET || 
            registerStatus == RegisterType.REGISTER_ERROR ||
            registerStatus == RegisterType.REGISTER_SUCCESS) {
                return this.renderOver();
            } else {
                return this.renderInit();
            }
    }

    getHeadTitle = ()=>{
        const{localCabinet} = this.state;
        let baseName = DataCenter.getTunnleBaseInfo();
        return baseName + (localCabinet.gateName ? ("  " +localCabinet.gateName) : "");
    }

    renderHeader() {
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <TouchableOpacity style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}
                    onPress={()=>{
                        const{navigation} = this.props;
                        if (Date.now() - this.clickTime > 2000) {
                            this.clickTime = Date.now();
                            this.clickCount = 0;
                          } else {
                            this.clickCount += 1;
                            if (this.clickCount >= 5) {
                              this.clickCount = 0;
                              navigation.navigate("Home");
                            }
                          }
                    }}>
                    <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                    <View style={{alignItems:'center', justifyContent:'center', marginLeft: scaleSize(20), width:scaleSize(100), borderRadius:scaleSize(6), height:scaleSize(40), backgroundColor: Colors.calm_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>
                        {"本柜"}</Text>
                    </View>
                </TouchableOpacity>
                {/* <TouchableOpacity style={{position:'absolute',top:0, right:0, width:200, height: scaleSize(88)}}
                    onPress={()=>{
                        const{navigation} = this.props;
                        if (Date.now() - this.clickTime > 2000) {
                            this.clickTime = Date.now();
                            this.clickCount = 0;
                          } else {
                            this.clickCount += 1;
                            if (this.clickCount >= 5) {
                              this.clickCount = 0;
                              navigation.navigate("Home");
                            }
                          }
                    }}>
                </TouchableOpacity> */}
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(150), height:scaleSize(88)}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备调试"}
                    onPress={()=>{
                        const{navigation} = this.props;
                        navigation.navigate("DebugDevice");
                }}/>
            </View>
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Main')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Colony')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('SingleHole')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceSummary')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceInfo')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
            </View>
    }

    render() {
        return <SafeAreaView style={styles.container}>
            {this.renderHeader()}
            <View style={{flex:1, paddingHorizontal: scaleSize(47), paddingVertical:scaleSize(30)}}>
            {this.renderContent()}
            </View>
            <CommonDrawer ref={(r) => {this.selectDrawer = r;}} contentView={this.renderMenuDrawer()}/>
            </SafeAreaView>
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1, 
        flexDirection:'column',
        backgroundColor: Colors.page_bg_color,
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
    cardContainer:{
        height:scaleSize(548),
        flexDirection:'column',
        backgroundColor: Colors.white,
        borderRadius: scaleSize(6),
        paddingHorizontal: scaleSize(30),
        paddingVertical: scaleSize(40),
    },
    input:{
        fontSize: FontSize.h3_font,
        marginLeft:scaleSize(10), 
        backgroundColor:'#F5F5FF', 
        width:scaleSize(400), 
        height:scaleSize(72),
        paddingVertical:0,
        borderWidth:1, 
        borderColor: Colors.border_color
    },
    cancelBtn:{
        paddingVertical:0, 
        backgroundColor: Colors.second_button_color, 
        width:scaleSize(260), 
        height:scaleSize(64)
    },
    sureBtn:{
        paddingVertical:0, 
        marginLeft:scaleSize(30), 
        backgroundColor: Colors.button_color, 
        width:scaleSize(260), 
        height:scaleSize(64)
    }
});